package com.hollysys.hollimsa.common.filter;


import com.hollysys.hollimsa.common.filter.tenantinfo.TenantInfo;
import com.hollysys.hollimsa.common.filter.tenantinfo.TenantInfoContext;
import com.hollysys.hollimsa.common.result.AjaxObject;
import com.hollysys.hollimsa.common.tools.JacksonUtil;
import com.hollysys.hollimsa.common.tools.ResponseUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 租户信息过滤器
 *
 * @author shaoguopeng
 */
public class TenantInfoContextFilter extends OncePerRequestFilter {

    private static final String TENANT_NAME_HEADER = "tenant";

    private static final String PROJECT_NAME_HEADER = "project";

    @Value("${app.devMode:false}")
    private boolean devMode;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            String tenantName = req.getHeader(TENANT_NAME_HEADER);
            String projectName = req.getHeader(PROJECT_NAME_HEADER);
            TenantInfo tenantInfo;

            if (!devMode) {
                if (tenantName == null || projectName == null) {
                    ResponseUtil.writeJson(response,JacksonUtil.toJSON(AjaxObject.customFail("需要Tenant和Project的header信息", "")));
                    return;
                }
                tenantInfo = new TenantInfo(tenantName, projectName);
            } else {
                tenantInfo = new TenantInfo(TENANT_NAME_HEADER, PROJECT_NAME_HEADER);
            }
            TenantInfoContext.setTenantInfo(tenantInfo);
            filterChain.doFilter(req, response);
        }finally {
            TenantInfoContext.remove();
        }
    }

}
